package cn.pb.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import cn.pb.domin.User;
import cn.pb.exception.UserExistExeception;
import cn.pb.exception.UserUnactiveException;
import cn.pb.service.UserService;
import cn.pb.utils.SendEmailUtil;

/**
 * @ClassName UserController类
 * @Author whw
 * @Date 2017年9月6日 上午11:09:33
 * @Version 1.0
 * @Description 用户控制层
 */
@Controller
@SessionAttributes("user")
@RequestMapping("/user") // 表示请求的父目录
public class UserController {
	@Autowired
	private UserService us;

	// 判断用户登陆
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(User user, Model model) {
		User login = null;
		try {
			login = us.login(user);
			if (login != null) {
				model.addAttribute("user", login);
			}
		} catch (UserUnactiveException e) {
			model.addAttribute("usernotexistmsg", "邮箱未激活！");
		}
		return login != null ? "/" : "/login.jsp";
	}

	// 判断用户是否存在
	@RequestMapping(value = "/isUserExist", method = RequestMethod.POST)
	public @ResponseBody String isUserExist(String uemail, Model model) {
		return us.isUserExist(uemail) == null ? "false" : "true";
	}

	// 用户注册
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(User user, Model model) {
		try {
			us.register(user);
			StringBuffer sb = new StringBuffer();
			sb.append("<h1>恭喜你！离注册成功只差一步了");
			sb.append("<a href='http://localhost:8080/personalblog/user/active?uemail=" + user.getUemail() + "'>");
			sb.append("<font color='red' >点击这里</font></a>激活吧！</h1>");
			SendEmailUtil.sendEmail("博客激活邮件", sb.toString(), user.getUemail());
		} catch (UserExistExeception e) {
			model.addAttribute("userexistmsg", "对不起该邮箱已经注册！不能再次注册。");
			return "/login.jsp";
		}
		model.addAttribute("regmsg", "注册成功！快去邮箱激活账号吧！");
		return "/regsuccess.jsp";
	}

	@RequestMapping(value = "/active", method = RequestMethod.GET)
	public String active(String uemail, Model model) {
		if ("true".equals(us.isUserExist(uemail).getUactive())) {
			model.addAttribute("regmsg", "该邮箱已经激活不用再次激活！");
		} else if (!us.active(uemail)) {
			model.addAttribute("regmsg", "激活失败！请重试！");
		} else {
			model.addAttribute("regmsg", "激活成功了！快去登录");
		}
		return "/regsuccess.jsp";
	}

	@RequestMapping(value = "/activeToJson", method = RequestMethod.POST)
	public @ResponseBody String activeToJson(String uemail) {
		if ("true".equals(us.isUserExist(uemail).getUactive())) {
			return "true";
		}
		return "false";
	}
}
